package com.wkg.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.AbstractJsonParser;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtils {

    // 私有构造函数，防止实例化
    private JacksonUtils() {}

    /**
     * 单例 ObjectMapper，用于序列化/反序列化 JSON
     */
    private final static ObjectMapper OBJECT_MAPPER;

    // 静态初始化 ObjectMapper 实例
    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    // 获取 ObjectMapper 实例
    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * 封装执行逻辑（无异常类型传入）
     * @param parser 实际执行的逻辑
     */
    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JsonParseException.class);
    }

    /**
     * 封装执行逻辑（传入需要拦截的异常类型）
     * 如果抛出的异常类型是指定的，就抛 JsonParseException，否则抛 IllegalStateException
     */
    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }

    /**
     * 将对象序列化成 JSON 字符串
     */
    public static String writeValueAsString(Object object) {
        return JacksonUtils.tryParse(() -> JacksonUtils.getObjectMapper().writeValueAsString(object));
    }

    /**
     * 将 JSON 字符串反序列化为对象
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return JacksonUtils.tryParse(() -> JacksonUtils.getObjectMapper().readValue(content, valueType));
    }

    /**
     * 将 JSON 字符串反序列化为 List<T> 类型的集合
     */
    public static <T> T readListValue(String content, Class<?> paramClasses) {
        JavaType javaType = JacksonUtils.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class, paramClasses);
        return JacksonUtils.tryParse(() -> JacksonUtils.getObjectMapper().readValue(content, javaType));
    }
}